package com.ihr360.excel.convertor;

import com.google.common.collect.Lists;
import com.ihr360.excel.logs.ExcelLogItem;
import com.ihr360.excel.logs.ExcelLogType;
import com.ihr360.excel.model.dto.SpreadsheetJournal;
import com.ihr360.excel.model.type.JournalType;
import com.ihr360.hibernate.type.util.StringUtils;
import org.apache.commons.collections.CollectionUtils;

import java.text.MessageFormat;
import java.util.Date;
import java.util.List;

public class ExcelLogToJournal {

    public static SpreadsheetJournal logItemToJournal(Date currentDate, ExcelLogItem logItem, JournalType journalType, Integer rowNum, String companyId) {
        SpreadsheetJournal journal = new SpreadsheetJournal();

        ExcelLogType logType = logItem.getLogType();
        journal.setLogType(logType);

        String defaultMsg = logItem.getDefaultLogMsg();
        if (ExcelLogType.CUSTOM_LOG_TYPE != logType) {
            defaultMsg = MessageFormat.format(logType.getNoLineNumberMsg(), logItem.getArgs());
        }
        String msgKey = StringUtils.isEmpty(logItem.getLogMsgKey()) ? logType.getLogKey() : logItem.getLogMsgKey();

        journal.setDefaultLogMsg(defaultMsg);
        journal.setLogMsgKey(msgKey);
        journal.setArgs(logItem.getArgs());
        journal.setCompanyId(companyId);
        journal.setCreatedAt(currentDate);
        journal.setUpdatedAt(currentDate);
        journal.setRowNum(rowNum);
        journal.setType(journalType);
        return journal;
    }

    public static List<SpreadsheetJournal> getJournals(List<ExcelLogItem> logItems, JournalType journalType, Integer rowNum, String companyId) {
        Date currentDate = new Date();
        if (CollectionUtils.isEmpty(logItems)) {
            return Lists.newArrayList();
        }
        List<SpreadsheetJournal> journals = Lists.newArrayListWithCapacity(logItems.size());
        for (ExcelLogItem logItem : logItems) {
            SpreadsheetJournal journal = ExcelLogToJournal.logItemToJournal(currentDate, logItem, journalType, rowNum, companyId);
            journals.add(journal);
        }
        return journals;
    }


}
